package com.cityfood.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cityfood.common.pojo.CityFoodResult;

public class LoginInterceptor  implements HandlerInterceptor {


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		CityFoodResult result = new CityFoodResult();

		// intercept
		HttpSession session = request.getSession(false);
		if(session !=null){
			return true;  //正常执行controller
		}else{
			result.setCode(201);
			result.setMsg("登陆失败");
			result.setData("");
			this.sentJsonMsg(response, result);
			return false;
		}

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle run!");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion run!");
		
	}
	
	private void sentJsonMsg(HttpServletResponse response,CityFoodResult result) throws IOException{
		response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        
        writer.print(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat));
        writer.close();
        response.flushBuffer();
	}
}
	